<template>
  <div>
    <a-modal
      v-model="visible"
      title="选择需要的增值服务"
      :width="1400"
      :maskClosable="false"
      @ok="onSubmit"
      @cancel="onCancel"
    >
      <a-spin :spinning="loading">
        <a-table
          bordered
          size="middle"
          :row-key="(record, index) => index"
          :columns="zxColumns"
          :data-source="zxData"
          :pagination="pagination"
          :scroll="{ y: 700, x: 1800 }"
        >
          <template slot="xu" slot-scope="text,record,index">
            {{ index + 1 }}
          </template>
          <template slot="cbx" slot-scope="text,record,index">
            <a-checkbox :checked="addForm['ext_' + index + '_' + text.ext_id]" @change="(e) => onChange(e,index,text.ext_id,text.price)">{{text.name}} * {{text.price}}</a-checkbox>
          </template>
          <template slot="ipt" slot-scope="text,record,index">
            <a-input-number
              :min="0"
              style="width:100px"
              :default-value="addForm['ext_' + index + '_' + text.ext_id]"
              @change="(value) => onNumberChange(value,text.ext_id,index)"
              @blur="onBlur(text.ext_id,index,text.price)"
              @focus="onFocus(text.ext_id, index)"
            >
            </a-input-number> * {{text.price}}
          </template>
          <template slot="row_total" slot-scope="text,record">
            <div class="total">{{record.check_total + record.ipt_total}}</div>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
  import storage from 'store'
  // import { pinyin } from 'pinyin-pro'
  import { getAddItem } from '@/api/contract'

  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      businessName: {
        type: String,
        default: ''
      },
      businessNum: {
        type: Number,
        default: 0
      }
    },
    name: 'ExtModal2',
    data () {
      return {
        visible: true,
        loading: true,
        addForm: {},
        beforeForm: {},
        zxColumns: [
          {
            title: '序号',
            scopedSlots: { customRender: 'xu' },
            width: '80px'
          },
          {
            title: '业务名称',
            dataIndex: 'business_name'
          }
        ],
        zxData: [],
        typeOpts: {},
        pagination: {},
        extOpts: {},
        extAmount: 0
      }
    },
    created () {
      this.getExt()
    },
    methods: {
      getExt () {
        const app = this
        app.loading = true
        if (storage.get('EXT_AMOUNT')) {
          for (const k in storage.get('EXT_AMOUNT')) {
            if (app.businessId === k) {
              app.zxColumns = storage.get('EXT_COLUMNS')[k]
              app.addForm = storage.get('EXT_ADDFORM')[k]
              app.extAmount = storage.get('EXT_AMOUNT')[k]
              app.beforeForm = storage.get('EXT_BEFOREFORM')[k]
              app.zxData = storage.get('EXT_DATA')[k]
              app.pagination = storage.get('EXT_PAGINATION')[k]
              app.loading = false
            } else {
              console.log(2)
            }
          }
        } else {
          this.getAddExt()
        }
      },
      getAddExt () {
        const app = this
        const total = {}
        const arr = []
        getAddItem(app.businessId).then(res => {
          app.typeOpts = res.result.typeOpts
          app.extOpts = res.result.data
          for (let i = 0; i < res.result.data.length; i++) {
            const data = {}
            data['title'] = res.result.data[i].name
            // data['dataIndex'] = pinyin(res.result.data[i].name, { toneType: 'none' }).replace(/\s*/g, '')
            data['dataIndex'] = 'ext' + '_' + i + '_' + res.result.data[i].ext_id
            if (res.result.data[i].type === 'count') data['scopedSlots'] = { customRender: 'ipt' }
            else data['scopedSlots'] = { customRender: 'cbx' }
            app.zxColumns.push(data)
          }
          total['title'] = '小计'
          total['scopedSlots'] = { customRender: 'row_total' }
          arr.push(total)
          app.zxColumns = app.zxColumns.concat(arr)
        }).finally(() => {
          for (let i = 0; i < app.businessNum; i++) {
            const arr = {}
            arr['business_name'] = app.businessName
            arr['check_total'] = 0
            arr['ipt_total'] = 0
            for (let j = 0; j < app.extOpts.length; j++) {
              arr['ext_' + j + '_' + app.extOpts[j].ext_id] = app.extOpts[j]
              if (app.extOpts[j].type === 'count') {
                app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
                app.beforeForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
              } else {
                app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = false
              }
            }
            app.zxData.push(arr)
          }
          app.pagination['pageSize'] = app.businessNum
          app.loading = false
        })
      },
      onCancel () {
        this.visible = false
        this.$emit('cancel', this.visible)
      },
      onSubmit () {
        const app = this
        const data = {}
        app.extAmount = 0
        for (const k in app.addForm) {
          //
          if (typeof app.addForm[k] === 'number') {
            data['bs[' + app.businessId + '][' + 'key' + k.match(/_(\S*)_/)[1] + '][' + k.substring(k.lastIndexOf('_') + 1) + '][count]'] = app.addForm[k]
          } else if (typeof app.addForm[k] === 'boolean') {
            if (app.addForm[k]) {
              data['bs[' + app.businessId + '][' + 'key' + k.match(/_(\S*)_/)[1] + '][' + k.substring(k.lastIndexOf('_') + 1) + '][count]'] = 1
            }
          }
        }
        for (const k in app.zxData) {
          let amount = 0
          amount = app.zxData[k].check_total + app.zxData[k].ipt_total
          app.extAmount = app.extAmount + amount
        }
        const data1 = {}
        const data2 = {}
        const data3 = {}
        const data4 = {}
        const data5 = {}
        const data6 = {}
        const data7 = {}
        data1[app.businessId] = app.zxData
        storage.set('EXT_DATA', data1)
        data2[app.businessId] = data
        storage.set('EXT_VALUE', data2)
        data3[app.businessId] = app.extAmount
        storage.set('EXT_AMOUNT', data3)
        data4[app.businessId] = app.addForm
        storage.set('EXT_ADDFORM', data4)
        data5[app.businessId] = app.beforeForm
        storage.set('EXT_BEFOREFORM', data5)
        data6[app.businessId] = app.pagination
        storage.set('EXT_PAGINATION', data6)
        data7[app.businessId] = app.zxColumns
        storage.set('EXT_COLUMNS', data7)
        this.$emit('change', app.businessId)
      },
      onNumberChange (value, id, index) {
        const app = this
        app.loading = true
        app.addForm['ext_' + index + '_' + id] = value
        app.$set(this.addForm, `ext_${index}_${id}`, value)
        app.loading = false
      },
      onBlur (id, index, price) {
        const app = this
        if (app.beforeForm['ext_' + index + '_' + id] === 0) {
          app.zxData[index].ipt_total += app.addForm['ext_' + index + '_' + id] * price
        } else {
          if (app.beforeForm['ext_' + index + '_' + id] > app.addForm['ext_' + index + '_' + id]) {
            app.zxData[index].ipt_total -= (app.beforeForm['ext_' + index + '_' + id] - app.addForm['ext_' + index + '_' + id]) * price
          } else {
            app.zxData[index].ipt_total += (app.addForm['ext_' + index + '_' + id] - app.beforeForm['ext_' + index + '_' + id]) * price
          }
        }
      },
      onFocus (id, index) {
        this.beforeForm['ext_' + index + '_' + id] = this.addForm['ext_' + index + '_' + id]
      },
      onChange (e, index, id, price) {
        const app = this
        app.loading = true
        if (e.target.checked) {
          app.zxData[index].check_total = Number(app.zxData[index].check_total + parseInt(price))
        } else {
          app.zxData[index].check_total = Number(app.zxData[index].check_total - parseInt(price))
        }
        app.addForm['ext_' + index + '_' + id] = e.target.checked
        app.$set(this.addForm, `ext_${index}_${id}`, e.target.checked)
        app.loading = false
      }
    }
  }
</script>

<style scoped>
  .total {
    font-weight: bold;
    font-size: 14px;
    color: #f00
  }
</style>
